import * as xlsx from 'xlsx'
import type { WorkBook, WorkSheet } from 'xlsx'
import type { JsonToSheet, JsonToMultipleSheet } from './typing'
const { utils, writeFile } = xlsx
import { cloneDeep } from 'lodash-es'

const DEF_FILE_NAME = '统计分析.xlsx'
export function jsonToSheetXlsx<T = any>({
  data,
  header,
  filename = DEF_FILE_NAME,
  json2sheetOpts = {},
  write2excelOpts = { bookType: 'xlsx' },
}: JsonToSheet<T>) {
  const arrData = [...data]
  if (header) {
    arrData.unshift(header)
    json2sheetOpts.skipHeader = true
  }

  const worksheet = utils.json_to_sheet(arrData, json2sheetOpts)
  // const worksheet1 = utils.json_to_sheet(arrData, json2sheetOpts)

  const workbook: WorkBook = {
    SheetNames: [filename],
    Sheets: {
      [filename]: worksheet,
    },
  }
  writeFile(workbook, filename, write2excelOpts)
}

export function jsonsToMultipleSheetXlsx<T = any>({
  datas,
  headers,
  filenames = [],
  json2sheetOpts = {},
  write2excelOpts = { bookType: 'xlsx' },
  xlsxName,
}: JsonToMultipleSheet<T>) {
  const arrDatas = cloneDeep(datas)
  const arrHeaders = cloneDeep(headers)

  const dic: { [sheet: string]: WorkSheet } = {}
  json2sheetOpts.skipHeader = true
  arrDatas.map((data, index) => {
    const header = arrHeaders[index]
    const fileName = filenames[index]
    data.unshift(header)
    const worksheet = utils.json_to_sheet(data, json2sheetOpts)
    dic[fileName] = worksheet
    return worksheet
  })

  const workbook: WorkBook = {
    SheetNames: filenames,
    Sheets: dic,
  }

  writeFile(workbook, xlsxName, write2excelOpts)
}
// const worksheet = utils.json_to_sheet(arrData, json2sheetOpts)
// const worksheet1 = utils.json_to_sheet(arrData, json2sheetOpts)

// const workbook: WorkBook = {
//   SheetNames: ['1', '2'],
//   Sheets: {
//     '1': worksheet,
//     '2': worksheet1,
//   },
// }
